<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import orderApi from '@/api/order_api.js'
import goodsApi from '@/api/goods_api.js'
import userApi from '@/api/user_api.js'

// 表格数据
const tableData = ref([])
const total = ref(0)
// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  username: '', // 修改为username字段
  goods_name: '',
  status: '',
})

// 要修改或者新增的数据
const obj = ref({})

// 用户名到用户ID的映射
const userMap = ref({})

// 获取用户信息
const getUserInfo = async (userId) => {
  if (!userMap.value[userId]) {
    try {
      const userResult = await userApi.getUserById(userId)
      if (userResult && userResult.username) {
        userMap.value[userId] = userResult.username
      }
    } catch (error) {
      console.error(`获取用户${userId}信息失败:`, error)
    }
  }
  return userMap.value[userId]
}

// 查询订单列表
const search = async () => {
  try {
    // 处理查询参数
    const queryParams = { ...searchObj.value };

    // 如果输入了订单号，转换为实际ID进行精确查询
    if (queryParams.id) {
      // 从格式化ID中提取实际ID（去掉日期前缀）
      const match = queryParams.id.match(/X\d{4}(\d{3})/);
      if (match) {
        queryParams.id = parseInt(match[1], 10);
      } else {
        // 如果格式不匹配，尝试直接使用输入值
        const numericId = parseInt(queryParams.id, 10);
        if (!isNaN(numericId)) {
          queryParams.id = numericId;
        }
      }
    }

    // 如果有用户名查询条件，先查询用户ID
    if (searchObj.value.username) {
      try {
        // 使用用户分页接口查找用户
        const userResult = await userApi.getUserPage(1, 100, { username: searchObj.value.username });
        if (userResult && userResult.records && userResult.records.length > 0) {
          // 找到匹配的用户，使用第一个匹配用户的ID进行查询
          queryParams.user_id = userResult.records[0].id;
        } else {
          // 没有找到匹配的用户，设置一个不可能存在的用户ID
          queryParams.user_id = -1;
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        ElMessage.error("查询用户信息失败");
      }
    }

    console.log('发送的查询参数:', queryParams)
    const result = await orderApi.getOrderPage(searchObj.value.current, searchObj.value.limit, queryParams);
    console.log('收到的响应数据:', result)

    // 处理订单数据，获取商品名称和用户名
    if (result.records) {
      for (let i = 0; i < result.records.length; i++) {
        const order = result.records[i];

        // 如果订单中没有商品名称但有goods_id，则获取商品名称
        if (!order.goods_name && order.goods_id) {
          try {
            const goodsResult = await goodsApi.getGoodsById(order.goods_id);
            if (goodsResult || goodsResult.data) {
              order.goods_name = goodsResult.name;
            }
          } catch (error) {
            console.error('获取商品信息失败:', error);
          }
        }

        // 获取用户名
        if (order.user_id && !userMap.value[order.user_id]) {
          await getUserInfo(order.user_id)
        }
        order.username = userMap.value[order.user_id] || order.user_id;
      }
    }

    tableData.value = result.records
    total.value = result.total
  } catch (error) {
    console.error('查询订单列表时出错:', error)
    tableData.value = []
    total.value = 0
  }
}

// 页面加载完成后查询数据
onMounted(() => {
  search()
})

// 重置查询条件
const resetSearch = () => {
  searchObj.value.id = ''
  searchObj.value.username = '' // 修改为username
  searchObj.value.goods_name = ''
  searchObj.value.status = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 处理删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await orderApi.deleteOrder(row.id)
        // 重新加载数据
        searchObj.value.current = 1
        await search()
      })
      .catch(() => {
      })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.replace('T', ' ')
}

// 格式化订单ID
const formatOrderId = (id, createTime) => {
  if (!id || !createTime) return id;

  const date = new Date(createTime);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const formattedId = String(id).padStart(3, '0');

  return `X${month}${day}${formattedId}`;
}

// 处理发货
const handleShip = async (row) => {
  try {
    const now = new Date();
    console.log("现在是:", now);
    // 为了保持时区正确性，我们使用本地时间格式化
    const sendTime = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + 'T' +
        String(now.getHours()).padStart(2, '0') + ':' +
        String(now.getMinutes()).padStart(2, '0') + ':' +
        String(now.getSeconds()).padStart(2, '0');

    // 更新订单状态为已发货(2)
    const updatedOrder = {
      ...row,
      status: 2,
      send_time: sendTime // 添加发货时间
    };
    await orderApi.updateOrder(updatedOrder);
    await search();
    ElMessage.success('发货成功');
  } catch (error) {
    ElMessage.error('发货失败: ' + error.message);
  }
}
</script>

<template>
  <div class="order-management">
    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="订单号">
        <el-input v-model="searchObj.id" placeholder="请输入订单号" clearable/>
      </el-form-item>
      <el-form-item label="用户名"> <!-- 修改为用户名 -->
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/> <!-- 修改为username -->
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchObj.goods_name" placeholder="请输入商品名称" clearable/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchObj.status" placeholder="请选择订单状态" clearable>
          <el-option label="未支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
          <el-option label="已发货" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="订单ID" width="120">
        <template #default="scope">
          {{ formatOrderId(scope.row.id, scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100"> <!-- 修改为username -->
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名称" width="200"></el-table-column>
      <el-table-column prop="goods_count" label="数量" width="80"></el-table-column>
      <el-table-column prop="goods_price" label="商品单价" width="100">
        <template #default="scope">
          ¥{{ scope.row.goods_price }}
        </template>
      </el-table-column>
      <el-table-column label="总价" width="100">
        <template #default="scope">
          ¥{{ (scope.row.goods_price * scope.row.goods_count).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="scope">
          <span v-if="scope.row.status === 0">未支付</span>
          <span v-else-if="scope.row.status === 1">已支付</span>
          <span v-else-if="scope.row.status === 2">已发货</span>
          <span v-else-if="scope.row.status === 3">已完成</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column prop="pay_time" label="支付时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 1">{{ formatDateTime(scope.row.pay_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="send_time" label="发货时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 2">{{ formatDateTime(scope.row.send_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="get_time" label="收货时间" width="180">
        <template #default="scope">
          <span v-if="scope.row.status >= 3">{{ formatDateTime(scope.row.get_time) }}</span>
          <span v-else>---</span>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="处理按钮" width="180">
        <template #default="scope">
          <el-button
              size="small"
              type="warning"
              @click="handleShip(scope.row)"
              v-if="scope.row.status == 1"
          >
            发货
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
.order-management {
  padding: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}
</style>
